package netty.nio;

import netty.ByteBufferUtil;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * @Author: zhangrongqing
 * @Date: 2020/1/7 15:06
 */
public class SocketChannelServerDemo {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(9090);

        Selector selector = Selector.open();

        serverSocketChannel.socket().bind(inetSocketAddress);

        //设置为非阻塞
        serverSocketChannel.configureBlocking(false);

        //ServerSocketChannel注册到Selector上去
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        //循环等待客户端连接
        while(true){
            //选择事件
            if(selector.select(1000) == 0){
                System.out.println("无事件发生");
                continue;
            }

            //获取相关的SelectionKey集合
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();

            while(iterator.hasNext()){
                SelectionKey selectionKey = iterator.next();
                //连接上来生成SocketChannel
                if(SelectionKey.OP_ACCEPT == selectionKey.interestOps()){
                    //连接上来
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    //注册到selector上去,可以添加一个buffer
                    socketChannel.register(selector,SelectionKey.OP_READ);
                }
                if(SelectionKey.OP_READ == selectionKey.interestOps()){
                    SocketChannel channel = (SocketChannel)selectionKey.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(5);
                    ByteBufferUtil.readByteBuffer(channel,byteBuffer);
                }
                if(SelectionKey.OP_WRITE == selectionKey.interestOps()){

                }
                //手动删除key
                iterator.remove();

            }
        }

    }
}
